import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:feature_webview/webview_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';

class WebviewPage extends GetView<WebviewController> {
  InAppWebViewController? _appWebViewController;
  final String title;
  final String url;

  WebviewPage({super.key, this.title = "", this.url = ""});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        centerTitle: true,
        elevation: 3,
        shadowColor: const Color(0xFF000000),
        title: Text(
          title,
          style: TextStyle(fontSize: 18.sp, color: const Color(0xff223141)),
        ),
        leading: IconButton(
          onPressed: () async {
            if (await _appWebViewController?.canGoBack() == true) {
              _appWebViewController?.goBack();
            } else {
              Get.back();
            }
          },
          icon: Icon(Icons.arrow_back_ios, color: const Color(0xFF333333)),
        ),
        actions: [
          IconButton(
            onPressed: () async {
              _appWebViewController?.reload();
            },
            icon: Icon(Icons.refresh, color: const Color(0xFF333333)),
          ),
        ],
      ),
      body: Obx(
        () => Stack(
          children: [
            _buildAppView(() {
              controller.isLoading = false;
            }),
            _buildLoading(),
          ],
        ),
      ).backgroundColor(Color(0xFFFD7F39)),
    );
  }

  Widget _buildLoading() => controller.isLoading
      ? Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(
                'images/bg_webview.png',
                package: 'feature_webview',
              ), //mono repo 需要加package
              fit: BoxFit.fill,
              alignment: Alignment.topCenter,
            ),
          ),
          child: CircularProgressIndicator().tightSize(28).center(),
        )
      : SizedBox.shrink();

  Widget _buildAppView(VoidCallback onLoadStop) {
    return InAppWebView(
      initialUrlRequest: URLRequest(url: WebUri(url)),
      onWebViewCreated: (controller) {
        _appWebViewController = controller;
      },
      onLoadStop: (_, url) {
        onLoadStop();
      },
    );
  }
}
